package com.Khan.SocialRescueSys.controller.admin;

import com.Khan.SocialRescueSys.pojo.User;
import com.Khan.SocialRescueSys.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author Khan Liu
 * @date 2022/4/5 20:32
 */
@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @GetMapping("/admin")
    public String loginPage(){
        return "admin/login";
    }

    @PostMapping("/admin/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user = userService.checkUser(username, password);
        if(user != null){
            user.setPassword(null);
            session.setAttribute("user", user);
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            subject.login(token);
            return "admin/index";
        }catch (UnknownAccountException e){
            attributes.addFlashAttribute("msg", "用户名不存在");
            return "redirect:/admin";
        }catch (IncorrectCredentialsException e){
            attributes.addFlashAttribute("msg", "密码错误");
            return "redirect:/admin";
        }
    }

    @GetMapping("/admin/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/admin";
    }
}
